#region File Description
//-----------------------------------------------------------------------------
// SpinningTriangleControl.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System.Diagnostics;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using CreamX.Framework.Game;
using System.Drawing;
using CreamX.Framework;

using Microsoft.Xna.Framework;
using CreamX.Framework.Game.GameEngine;
using CreamXStudio.XNARenderer;
using CreamX.Framework.SceneGraph;

#endregion

namespace CreamXStudio
{
    class LevelRendererControl : GraphicsDeviceControl
    {
        PrimitiveBatch primitiveBatch;
        public  CreamXObject _pickedUpObject;
        public CreamXSceneData _data;
        bool _cameraselected;
        public ContentBuilder _builder;
        public bool ShowTemplateObjects=true;
        PrimitiveBatch _batch;
        public void SetData(CreamXSceneData data,ContentBuilder builder)
        {
            _builder = builder;
            _data = data;
        }
        Stopwatch timer;

        protected override void Initialize()
        {
            primitiveBatch = new PrimitiveBatch(GraphicsDevice);
            // Start the animation timer.
            timer = Stopwatch.StartNew();
            // Hook the idle event to constantly redraw our animation.
            Application.Idle += delegate { Invalidate(); };
            _batch = new PrimitiveBatch(GraphicsDevice);
        }

        protected override void Draw()
        {
            timer.Stop();
            float time = (float)timer.Elapsed.TotalSeconds;
            timer.Reset();
            timer.Start();
            GraphicsDevice.Clear(Microsoft.Xna.Framework.Graphics.Color.CornflowerBlue);
            //Draw Grid
            DrawGrid();

            if (_data != null)
            {
                DrawCameraOutline();
                SpriteBatch __d = new SpriteBatch(GraphicsDevice);

                __d.Begin();
                //Render normal scene
                CreamXGameEngine.Instance.EngineRender(time, __d,true);

                if (ShowTemplateObjects)
                {
                    foreach (CreamXObject obj in _data.TemplateObjects)
                    {
                        if (obj.Material == null)
                            continue;
                        if (obj is CreamXAnimatedObject)
                            __d.Draw(obj.Material.Texture, _data.Camera.GetRenderPosition(obj.Position),
                                ((CreamXAnimatedObject)obj).GetSourcRectForFrame(), Microsoft.Xna.Framework.Graphics.Color.White, obj.Rotation, obj.Origin,
                                _data.Camera.GetRenderScale(obj.Scale), SpriteEffects.None, 0);
                        else
                            __d.Draw(obj.Material.Texture, _data.Camera.GetRenderPosition(obj.Position), null, Microsoft.Xna.Framework.Graphics.Color.White,
                        obj.Rotation, obj.Origin, _data.Camera.GetRenderScale(obj.Scale), SpriteEffects.None, 0);
                    }
                }
                __d.End();
                if (SelectedObject != null)
                {
                    primitiveBatch.DrawBox(_data.Camera.GetRenderPosition(SelectedBoxMin),
                            _data.Camera.GetRenderPosition(SelectedBoxMax), Microsoft.Xna.Framework.Graphics.Color.White);

                    primitiveBatch.DrawCircle(_data.Camera.GetRenderPosition(SelectedObject.Position), 5 * _data.Camera.Zoom,
                        Microsoft.Xna.Framework.Graphics.Color.Blue);

                }

               // __d.Begin();
               // CreamXGameEngine.Instance.EngineRenderGUI(time, __d);
               // __d.End();
            }
            timer.Start();
        }

        private void DrawCameraOutline()
        {
            primitiveBatch.DrawBox(_data.Camera.GetRenderPosition(Vector2.Zero),
               _data.Camera.GetRenderPosition(_data.Camera.Size), Microsoft.Xna.Framework.Graphics.Color.Blue);
        }

        private void DrawGrid()
        {
            
            int rows = GraphicsDevice.Viewport.Height / 50;
            int cols = GraphicsDevice.Viewport.Width / 50;
            for (int i = 0; i < rows; i++)
            {
                for (int x = 0; x < cols; x++)
                {
                    primitiveBatch.DrawLine(new Microsoft.Xna.Framework.Vector2(x * 50, 0), 
                        new Microsoft.Xna.Framework.Vector2(x * 50, GraphicsDevice.Viewport.Height), Microsoft.Xna.Framework.Graphics.Color.White);
                }
                primitiveBatch.DrawLine(new Microsoft.Xna.Framework.Vector2(0, i * 50), new Microsoft.Xna.Framework.Vector2(GraphicsDevice.Viewport.Width, i * 50), Microsoft.Xna.Framework.Graphics.Color.White);
            }
        }
        System.Drawing.Point _lastPos;
        protected override void OnMouseMove(MouseEventArgs e)
        {
            Vector2 __diff = new Vector2(e.X - _lastPos.X, e.Y - _lastPos.Y);
            if (_pickedUpObject != null)
            {
                //_pickedUpObject.SetPosition(e.X, e.Y);
               // if(!(_pickedUpObject is CreamXTileGrid))
                    _pickedUpObject.Move(__diff.X / _data.Camera.Zoom, __diff.Y / _data.Camera.Zoom);


                SetSelectedBox(_pickedUpObject);

                this.Invalidate();
            }
            else if (_cameraselected)
            {
                _data.Camera.Move( new Vector2(-(__diff.X ),
                    -(__diff.Y )));
            }
            _lastPos = new System.Drawing.Point(e.X, e.Y);
            base.OnMouseMove(e);
        }

        protected override void OnDoubleClick(EventArgs e)
        {
            base.OnDoubleClick(e);
        }
        
        public void SetSelectedBox(CreamXObject obj)
        {
            Vector2 __tl = obj.Position
                    - (obj.Origin * obj.Scale);
            __tl -= new Vector2(1);

            Vector2 __br = __tl + new Vector2(obj.DisplayWidth + 1,
                obj.DisplayHeight + 1);
            if (obj is CreamXAnimatedObject)
            {
                __br = __tl + new Vector2(((CreamXAnimatedObject)obj).Animation.SizeX + 1,
                ((CreamXAnimatedObject)obj).Animation.SizeY + 1);
            }

            SelectedBoxMin = __tl;
            SelectedBoxMax = __br;
        }

        public Vector2 GetMapMousePosition(Vector2 pos)
        {
            if (_data == null) return Vector2.Zero;
            return (pos+ _data.Camera.Position) / _data.Camera.Zoom;
            //return universalMouse.Position + 
            //    CreamXGameEngine.Instance.SceneManager.CurrentScene.Camera.Position;
        }
        List<CreamXObject> _possibleObjects = new List<CreamXObject>();
        protected override void OnMouseDown(MouseEventArgs e)
        {
            _possibleObjects.Clear();
            if (_data == null)
                return;
            _pickedUpObject = null;
            _cameraselected = false;

            if (e.Button == MouseButtons.Left)
            {
                Vector2 __mapmou = GetMapMousePosition(new Vector2(e.X, e.Y));
                BoundingSphere __b = new BoundingSphere(new Vector3(__mapmou, 0),1);

                foreach (CreamXObject __o in _data.TemplateObjects)
                {
                    Vector2 __tl = __o.Position
                            - (__o.Origin*__o.Scale);
                    __tl -= new Vector2(1);

                    Vector2 __br = __tl + new Vector2(__o.DisplayWidth + 1,
                        __o.DisplayHeight + 1);
                    if (__o is CreamXAnimatedObject)
                    {
                        __br = __tl + new Vector2(((CreamXAnimatedObject)__o).Animation.SizeX + 1,
                        ((CreamXAnimatedObject)__o).Animation.SizeY + 1);
                    }
                    //__br-= new Vector2(1);
                    BoundingBox SelectedBox = new BoundingBox(new Vector3(__tl, 0), new Vector3(__br, 0));



                    if (SelectedBox.Intersects(__b))
                    {
                        _possibleObjects.Add(__o);
//                        _pickedUpObject = SelectedObject = __o;
  //                      SelectedBoxMin = __tl;
    //                    SelectedBoxMax = __br;
                        //break;
                    }
                }
                foreach (CreamXObject __o in _data.Objects)
                {


                    if (__o.Material == null)
                        continue;


                    Vector2 __tl = __o.Position
                        - (__o.Origin * __o.Scale);
                    __tl -= new Vector2(1);

                    Vector2 __br = __tl + new Vector2(__o.DisplayWidth + 1,
                        __o.DisplayHeight + 1);
                    if (__o is CreamXAnimatedObject)
                    {
                        __br = __tl + new Vector2(((CreamXAnimatedObject)__o).Animation.SizeX + 1,
                        ((CreamXAnimatedObject)__o).Animation.SizeY + 1);
                    }
                    //__br-= new Vector2(1);
                    BoundingBox SelectedBox = new BoundingBox(new Vector3(__tl, 0),
                        new Vector3(__br, 0));

                    if (SelectedBox.Intersects(__b))
                    {
                        _possibleObjects.Add(__o);
                        //_pickedUpObject = SelectedObject = __o;
                        //SelectedBoxMin = __tl;
                        //SelectedBoxMax = __br;
                       // break;
                    }
                }
                //foreach (CreamX.Framework.Game.GUI.GUIButton __o in _data.GUI.Buttons)
                //{
                //    if (__o.Material == null)
                //        continue;
                //    Vector2 __tl = __o.Position
                //        - __o.Origin;
                //    __tl -= new Vector2(1);

                //    Vector2 __br = __tl + new Vector2(__o.DisplayWidth + 1,
                //        __o.DisplayHeight + 1);

                //    //__br-= new Vector2(1);
                //    BoundingBox SelectedBox = new BoundingBox(new Vector3(__tl, 0),
                //        new Vector3(__br, 0));

                //    if (SelectedBox.Intersects(__b))
                //    {
                //        _possibleObjects.Add(__o);
                //        //_pickedUpObject = SelectedObject = __o;
                //        //SelectedBoxMin = __tl;
                //        //SelectedBoxMax = __br;
                //        // break;
                //    }
                //}
            }
            else if (_pickedUpObject == null && e.Button == MouseButtons.Right)
            {
                _cameraselected = true;
            }


            foreach (CreamXObject __o in _possibleObjects)
            {
                if(_pickedUpObject==null || __o.Layer > _pickedUpObject.Layer)
                    _pickedUpObject = __o;
            }
            if (_pickedUpObject != null)
            {
                Vector2 __tl = _pickedUpObject.Position
                       - _pickedUpObject.Origin;
                __tl -= new Vector2(1);

                Vector2 __br = __tl + new Vector2(_pickedUpObject.DisplayWidth + 1,
                    _pickedUpObject.DisplayHeight + 1);
                if (_pickedUpObject is CreamXAnimatedObject)
                {
                    __br = __tl + new Vector2(((CreamXAnimatedObject)_pickedUpObject).Animation.SizeX + 1,
                    ((CreamXAnimatedObject)_pickedUpObject).Animation.SizeY + 1);
                }
                //__br-= new Vector2(1);
                BoundingBox SelectedBox = new BoundingBox(new Vector3(__tl, 0),
                    new Vector3(__br, 0));
                SelectedBoxMin= __tl;
                SelectedBoxMax = __br;
                SelectedObject = _pickedUpObject;
            }

            base.OnMouseDown(e);
        }
        public CreamXObject SelectedObject;
        public Vector2 SelectedBoxMin;
        public Vector2 SelectedBoxMax;
        protected override void OnMouseUp(MouseEventArgs e)
        {
            _pickedUpObject = null;
            _cameraselected = false;
            base.OnMouseUp(e);
        }
        public bool DrawOutlines = true;

        public void UpdateObjects()
        {
            float time = (float)timer.Elapsed.TotalSeconds;
            CreamXGameEngine.Instance.EngineUpdate(time);
            //foreach (CreamXObject __u in _data.Objects)
            //{
            //    foreach (CreamXComponent com in __u.Components)
            //    {
            //        com.Update(time);
            //    }
            //}
            //foreach (CreamXObject __u in _data.TemplateObjects)
            //{
            //    foreach (CreamXComponent com in __u.Components)
            //    {
            //        com.Update(time);
            //    }
            //}
        }
    }





}
